package com.ruoyi.web.controller.system;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.QywxMessageService;
import com.ruoyi.system.domain.SysContract;
import com.ruoyi.system.domain.vo.QyWxMessage;
import com.ruoyi.system.service.ISysContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 合同Controller
 *
 * @author ruoyi
 * @date 2024-11-14
 */
@RestController
@RequestMapping("/system/contract")
public class SysContractController extends BaseController {
    @Autowired
    private ISysContractService sysContractService;

    @Autowired
    private QywxMessageService qywxMessageService;


    /**
     * 查询合同列表
     */
    @PreAuthorize("@ss.hasPermi('system:contract:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysContract sysContract) {
        startPage();
        List<SysContract> list = sysContractService.selectSysContractList(sysContract);
        return getDataTable(list);
    }

    /**
     * 查询合同状态数量
     */
    @PreAuthorize("@ss.hasPermi('system:contract:list')")
    @GetMapping("/queryContractStatusCounts")
    public AjaxResult queryContractStatusCounts() {
        startPage();
        List<HashMap<String, Integer>> list = sysContractService.getContractStatusCounts();
        return AjaxResult.success(list);
    }

    /**
     * 导出合同列表
     */
    @PreAuthorize("@ss.hasPermi('system:contract:export')")
    @Log(title = "合同", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysContract sysContract) {
        List<SysContract> list = sysContractService.selectSysContractList(sysContract);
        updateSysContractStatus(list);
        ExcelUtil<SysContract> util = new ExcelUtil<SysContract>(SysContract.class);
        util.exportExcel(response, list, "合同数据");
    }


    public void updateSysContractStatus(List<SysContract> list) {
        for (SysContract contract : list) {
            long betweenDay = DateUtil.between(new Date(), contract.getContractEndDate(), DateUnit.DAY, false);
            contract.setContractPeriod(DateUtil.betweenDay(contract.getContractStartDate(), contract.getContractEndDate(), true));
            contract.setTypeText(contract.getType() == 0 ? "正常" : "停用");
            if (betweenDay > 30) {
                contract.setStatusText("正常");
            } else if (betweenDay > 0) {
                contract.setStatusText("即将过期");
            } else {
                contract.setStatusText("已过期");
            }
        }
    }

    /**
     * 获取合同详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:contract:query')")
    @GetMapping(value = "/{contractId}")
    public AjaxResult getInfo(@PathVariable("contractId") Long contractId) {
        return success(sysContractService.selectSysContractByContractId(contractId));
    }


    /**
     * 新增合同
     */
    @PreAuthorize("@ss.hasPermi('system:contract:add')")
    @Log(title = "合同", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysContract sysContract) {
        return toAjax(sysContractService.insertSysContract(sysContract));
    }

    @PreAuthorize("@ss.hasPermi('system:contract:add')")
    @Log(title = "发送企业微信通知", businessType = BusinessType.INSERT)
    @PostMapping("/sendQyWxMsg")
    public AjaxResult sendQyWxMsg(@Validated @RequestBody QyWxMessage message) {
        if (StrUtil.isBlankIfStr(message.getMarkdown().getContent())){
            return AjaxResult.error("发送内容不能为空");
        }
        if (StrUtil.isBlankIfStr(message.getTouser())){
            return AjaxResult.error("接收人不能为空");
        }
        if (message.getMarkdown().getContent().length()>500){
            return AjaxResult.error("发送内容不能超过500个字符");
        }
        String result = this.qywxMessageService.sendMarkDownMsg(message.getTouser(), message.getMarkdown().getContent());
        if ("发送成功".equals(result)) {
            return AjaxResult.success(result);
        }
        return AjaxResult.error(result);
    }

    /**
     * 修改合同
     */
    @PreAuthorize("@ss.hasPermi('system:contract:edit')")
    @Log(title = "合同", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysContract sysContract) {
        return toAjax(sysContractService.updateSysContract(sysContract));
    }

    /**
     * 删除合同
     */
    @PreAuthorize("@ss.hasPermi('system:contract:remove')")
    @Log(title = "合同", businessType = BusinessType.DELETE)
    @DeleteMapping("/{contractIds}")
    public AjaxResult remove(@PathVariable Long[] contractIds) {
        return toAjax(sysContractService.deleteSysContractByContractIds(contractIds));
    }
}
